package neu.tour.activity;

/**
 * 地图页,显示用户位置、标注点、图片
 */

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;

import neu.tour.R;
import neu.tour.support.InitSystemBar;
import neu.tour.support.MyOrientationListener.OnOrientationListener;
import neu.tour.support.MyOrientationListener;
import neu.tour.support.Poi;


public class MainActivity extends Activity{

    private MapView mMapView = null; //地图View
    private BaiduMap mBaiduMap; //地图实例
    private LocationClient mLocationClient; //客户端
    public MyLocationListener mMyLocationListener; //监听器
    private LocationMode mCurrentMode = LocationMode.NORMAL; //定位模式
    private volatile boolean isFristLocation = true; //第一次定位
    private double mCurrentLantitude; //经度
    private double mCurrentLongitude; //纬度
    private float mCurrentAccracy; //精度
    private MyOrientationListener myOrientationListener; //方向传感器的监听器
    private int mXDirection;  //方向传感器X方向的值
    private BitmapDescriptor mIconMaker;  //全局bitmap
    private RelativeLayout mMarkerInfoLy;  //详细信息的布局
    private LayoutInflater mInflater;
    private int[] mImgIds ; //获取图片列表
    private int[] yearlist; //获取年代列表
    private int selectedImgId; //选中的图片作为参数
    private int oldselectedTag = -1;
    private int len = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        //不显示title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        InitSystemBar.initSystemBar(this);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        // 注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);

        init(); //初始化
    }
    
    private void init(){
        isFristLocation = true; // 第一次定位
        // 获取地图控件引用
        mMapView = (MapView) findViewById(R.id.id_bmapView);
        mMarkerInfoLy = (RelativeLayout) findViewById(R.id.id_marker_info);
        // 获得地图的实例
        mBaiduMap = mMapView.getMap();
        mIconMaker = BitmapDescriptorFactory.fromResource(R.drawable.marker);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(msu);
        initMyLocation();// 初始化定位
        initOritationListener();// 初始化方向传感器
        addInfosOverlay(Poi.poi);//在地图上添加标注点
        initMarkerClickEvent();//初始化标注点 click event
        initMapClickEvent();//初始化地图 click event
    }


    /**
     * 初始化定位相关代码
     */
    private void initMyLocation(){
        // 定位初始化
        mLocationClient = new LocationClient(this);
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);
        // 设置定位的相关配置
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(10000);
        mLocationClient.setLocOption(option);
    }


    /**
     * 实现实位回调监听
     */
    public class MyLocationListener implements BDLocationListener{
        @Override
        public void onReceiveLocation(BDLocation location){
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null){
                return;
            }
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mXDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mCurrentAccracy = location.getRadius();
//            System.out.println("asdf error code"+location.getLocType());
            mBaiduMap.setMyLocationData(locData);// 设置定位数据
            mCurrentLantitude = location.getLatitude();
            mCurrentLongitude = location.getLongitude();
            BitmapDescriptor mCurrentMarker = null;// 设置自定义图标
            MyLocationConfiguration config = new MyLocationConfiguration(
                    mCurrentMode, true, mCurrentMarker);
            mBaiduMap.setMyLocationConfigeration(config);
            if (isFristLocation){ // 第一次定位时，将地图位置移动到当前位置
                isFristLocation = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
            }
        }
    }


    /**
     * 初始化方向传感器
     */
    private void initOritationListener(){
        myOrientationListener = new MyOrientationListener(
                getApplicationContext());
        myOrientationListener
                .setOnOrientationListener(new OnOrientationListener() {
                    @Override
                    public void onOrientationChanged(float x) {
                        mXDirection = (int) x;
                        // 构造定位数据
                        MyLocationData locData = new MyLocationData.Builder()
                                .accuracy(mCurrentAccracy)
                                // 此处设置开发者获取到的方向信息，顺时针0-360
                                .direction(mXDirection)
                                .latitude(mCurrentLantitude)
                                .longitude(mCurrentLongitude).build();
                        mBaiduMap.setMyLocationData(locData);// 设置定位数据
                        BitmapDescriptor mCurrentMarker = null;// 设置自定义图标
                        MyLocationConfiguration config = new MyLocationConfiguration(
                                mCurrentMode, true, mCurrentMarker);
                        mBaiduMap.setMyLocationConfigeration(config);
                    }
                });
    }


    /**
     * 初始化图层
     */
    public void addInfosOverlay(List<Poi> pois){
        mBaiduMap.clear(); //清除地图上的控件
        LatLng latLng = null;
        OverlayOptions overlayOptions = null;
        Marker marker = null;
        for (Poi poi : pois){
            latLng = new LatLng(poi.getLat(), poi.getLng());// 位置
            overlayOptions = new MarkerOptions().position(latLng)
                    .icon(mIconMaker).zIndex(5);// 图标
            marker = (Marker) (mBaiduMap.addOverlay(overlayOptions));
            Bundle bundle = new Bundle();
            bundle.putSerializable("poi", poi);
            marker.setExtraInfo(bundle);
        }
    }


    /**
     * 初始化标注点的点击事件
     */
    private void initMarkerClickEvent(){
        mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener(){
            @Override
            public boolean onMarkerClick(final Marker marker){
                Poi poi = (Poi) marker.getExtraInfo().get("poi");// 获得marker中的数据
                InfoWindow mInfoWindow;// 构造InfoWindow用于显示详细信息
                // 生成一个TextView用于在地图中显示InfoWindow
                TextView location = new TextView(getApplicationContext());
                location.setBackgroundResource(R.drawable.location_tips);
                location.setPadding(30, 20, 30, 50);
                //计算并显示距离
                LatLng pmaker = new LatLng(poi.getLat(), poi.getLng());
                LatLng pme = new LatLng(mCurrentLantitude, mCurrentLongitude);
                double distance = (int)DistanceUtil.getDistance(pmaker, pme);
                String infostr = poi.getName() + "\n 距离：" + Double.toString(distance)+"米";
                location.setText(infostr);
                // 将marker所在的经纬度的信息转化成屏幕上的坐标
                final LatLng ll = marker.getPosition();
                Point p = mBaiduMap.getProjection().toScreenLocation(ll);
                p.y -= 47;
                LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);
                // 为弹出的InfoWindow添加点击事件
                mInfoWindow = new InfoWindow(location, llInfo,0);
                mBaiduMap.showInfoWindow(mInfoWindow);// 显示InfoWindow
                mMarkerInfoLy.setVisibility(View.VISIBLE);
                oldselectedTag = -1;// 弹出前恢复全局变量
                len = 0;
                popupInfo(mMarkerInfoLy, poi);// 弹出InfoWindow
                return true;
            }
        });
    }


    /**
     * 复用弹出面板mMarkerLy的控件
     */
    private class ViewHolder{
        LinearLayout poiImgList;
        TextView poiTitle;
    }


    /**
     * 根据info为布局上的控件设置信息
     */
    protected void popupInfo(RelativeLayout mMarkerLy, Poi poi){
        ViewHolder viewHolder = null;
        if (mMarkerLy.getTag() == null){
            viewHolder = new ViewHolder();// 添加tag
            viewHolder.poiImgList =
                    (LinearLayout) mMarkerLy.findViewById(R.id.id_gallery);
            viewHolder.poiTitle =
                    (TextView) mMarkerLy.findViewById(R.id.info_title);
            mMarkerLy.setTag(viewHolder);
        }
        viewHolder = (ViewHolder) mMarkerLy.getTag();
        mInflater = LayoutInflater.from(this);
        mImgIds = poi.getImgList();//获取图片列表
        yearlist = poi.getImgYear();//获取年代列表
        viewHolder.poiImgList.removeAllViews();//清除之前加载的view
        HorizontalScrollView vv = (HorizontalScrollView)
                mMarkerLy.findViewById(R.id.id_scroll);
        vv.scrollTo(0,0);//回滚到初始状态
        len = mImgIds.length;
        for (int i = 0; i < len; i++) {//循环添加图片和年代信息
            View view = mInflater.inflate(R.layout.galleryitem,
                    viewHolder.poiImgList, false);
            ImageView img = (ImageView) view.findViewById(R.id.imageView);
            img.setImageResource(mImgIds[i]);//添加图片
            img.setTag(i);// 给每一个图片添加tag
            ImageView flag = (ImageView) view.findViewById(R.id.selectedFlag);
            flag.setTag(i+"a");//添加图片右上角flag小图标
            img.setOnClickListener(new MyImgClickListener());            // 图片点击事件
            img.clearAnimation();
            TextView txt = (TextView) view.findViewById(R.id.textView);
            txt.setText(String.valueOf(yearlist[i]));// 添加年代
            viewHolder.poiImgList.addView(view);
        }
        // 设置title及超链接
        SpannableString mSpannableString =
                new SpannableString(poi.getTitle());
        mSpannableString.setSpan(new URLSpan(poi.getPath()), 0, mSpannableString.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        viewHolder.poiTitle.setText(mSpannableString);
        viewHolder.poiTitle.setMovementMethod(LinkMovementMethod.getInstance());
    }


    /**
     * 初始化地图点击事件
     */
    private void initMapClickEvent(){
        mBaiduMap.setOnMapClickListener(new OnMapClickListener(){

            @Override
            public boolean onMapPoiClick(MapPoi arg0){
                return false;
            }

            @Override
            public void onMapClick(LatLng arg0){
                mMarkerInfoLy.setVisibility(View.GONE);
                mBaiduMap.hideInfoWindow();
            }

        });

    }


    /**
     * 照片点击事件
     */
    public class MyImgClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            final ProgressDialog proDia = new ProgressDialog(MainActivity.this);
            proDia.setMessage("加载中，请稍候");
            proDia.onStart();
            new Thread(){
                public void run(){
                    try{
                        Thread.sleep(1000);
                    }
                    catch(Exception e){
                    }
                    finally{
                        //匿名内部类要访问类当中的数据，该数据必须为final
                        proDia.dismiss();//隐藏对话框
                    }
                }
            }.start();
            proDia.show();

            deleteOldSelected();// 清除以前选中图片的对号小图标
            int i = (int) v.getTag();// 显示对号小图标
            selectedImgId = mImgIds[i];
            LinearLayout gallery =
                    (LinearLayout)findViewById(R.id.id_gallery);
            ImageView flag = (ImageView) gallery.findViewWithTag(i+"a");
            flag.setVisibility(View.VISIBLE);
            oldselectedTag = i;

            Intent intent = new Intent();
            intent.setClass(MainActivity.this, CameraActivity.class);
            intent.putExtra("selectedImgId", selectedImgId);
            MainActivity.this.startActivity(intent);
        }
    }


    /**
     * 删除已有的图片右上角标注
     * 此段代码还需进一步修改
     */
    private void deleteOldSelected(){
        if(oldselectedTag != -1) {
            if(len>=oldselectedTag){
                LinearLayout gallery =
                        (LinearLayout)findViewById(R.id.id_gallery);
                ImageView oldflag = (ImageView)
                        gallery.findViewWithTag(oldselectedTag + "a");
                oldflag.setVisibility(View.INVISIBLE);
            }
        }
    }


    @Override
    protected void onStart(){
        // 开启图层定位
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()){
            mLocationClient.start();
        }
        // 开启方向传感器
        myOrientationListener.start();
        super.onStart();
    }


    @Override
    protected void onStop(){
        // 关闭图层定位
        mBaiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();

        // 关闭方向传感器
        myOrientationListener.stop();
        super.onStop();
    }


    @Override
    protected void onDestroy(){
        super.onDestroy();
        // 在activity执行onDestroy时执行mMapView.onDestroy()，
        // 实现地图生命周期管理
        mMapView.onDestroy();
        mIconMaker.recycle();
        mMapView = null;
    }


    @Override
    protected void onResume(){
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，
        // 实现地图生命周期管理
        mMapView.onResume();
    }


    @Override
    protected void onPause(){
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，
        // 实现地图生命周期管理
        mMapView.onPause();
    }
}